package com.kstech.ks_gaz01.sensorSetting

import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.blankii.androidlibrary.utils.CalcUtil
import com.chad.library.adapter4.BaseMultiItemAdapter
import com.kstech.ks_gaz01.data.SensorItem

import com.kstech.ks_gaz01.databinding.LayoutItemSensorMultiBinding
import com.kstech.ks_gaz01.databinding.LayoutSectionItemBinding

class SensorSettingMultiAdapter(data: List<SensorItem>) : BaseMultiItemAdapter<SensorItem>(data) {
    // 类型 1 的 viewholder
    class ItemVH(val viewBinding: LayoutItemSensorMultiBinding) :
        RecyclerView.ViewHolder(viewBinding.root)

    // 类型 2 的 viewholder
    class HeaderVH(val viewBinding: LayoutSectionItemBinding) :
        RecyclerView.ViewHolder(viewBinding.root)

    init {
        addItemType(ITEM_TYPE, object : OnMultiItemAdapterListener<SensorItem, ItemVH> {
            override fun onBind(holder: ItemVH, position: Int, item: SensorItem?) {
                // 绑定 item 数据
                holder.viewBinding.apply {
                    itemName.text = item!!.name
                    //判断单位是否为负数 gnh16检查到标定没有负数
                    itemValue.text = CalcUtil.Hex2IntStr(item.value!!, item.isNegative)
                }
            }

            override fun onCreate(context: Context, parent: ViewGroup, viewType: Int): ItemVH {
                // 创建 viewHolder
                val viewBinding = LayoutItemSensorMultiBinding.inflate(
                    LayoutInflater.from(context), parent, false
                )
                return ItemVH(viewBinding)
            }

        }).addItemType(
            SECTION_TYPE, object : OnMultiItemAdapterListener<SensorItem, HeaderVH> {
                override fun onBind(holder: HeaderVH, position: Int, item: SensorItem?) {
                    // 绑定 item 数据
                    holder.viewBinding.name.text = item!!.name
                }

                override fun onCreate(
                    context: Context, parent: ViewGroup, viewType: Int
                ): HeaderVH {
                    // 创建 viewholder
                    val viewBinding = LayoutSectionItemBinding.inflate(
                        LayoutInflater.from(context), parent, false
                    )
                    return HeaderVH(viewBinding)
                }

                override fun isFullSpanItem(itemType: Int): Boolean {//必须使用QuickGridLayoutManager 才可以满跨度
                    // 使用GridLayoutManager时，此类型的 item 是否是满跨度
                    return true
                }

            }).onItemViewType { position, list -> // 根据数据，返回对应的 ItemViewType
            if (list[position].isSection) {
                SECTION_TYPE
            } else {
                ITEM_TYPE
            }
        }
    }

    companion object {
        private const val ITEM_TYPE = 0
        private const val SECTION_TYPE = 1
    }
}